#encoding:utf-8
# @Time : 2021/8/25 0:29 
# @Author : 锦衣大镖客
# @File : ExcelUtils.py 
# @Software: PyCharm
# desc:
import os
import xlrd3

class Excel_Utils:
    path=os.path.join(os.path.dirname(__file__).split("api_test_frame")[0],"api_test_frame","test_data")
    def __init__(self,ExcelName,SheetName):
        """
        @ExcelName为test_data文件下的测试Excel表格
        @SheetName为测试表格里面的sheet名
        """
        self.ExcelName=ExcelName
        self.SheetName=SheetName
        self.sheet=self.__get_sheet #整个表格对象

    @property
    def __get_sheet(self):
        wb=xlrd3.open_workbook(self.path+os.sep+self.ExcelName)
        sheet=wb.sheet_by_name(self.SheetName)
        return sheet
    def get_row_count(self):
        # 获取整个行数
        row_count=self.sheet.nrows
        return row_count
    def get_col_count(self):
        # 获取整个列数
        col_count=self.sheet.ncols
        return col_count
    def get_cell_value(self,rlow_index, clow_index):
        # 获取表格的值
        cell_value=self.sheet.cell_value(rlow_index, clow_index)
        return cell_value

    def get_merged_value(self,rlow_index, clow_index):
        # 获取合并单元格的数据
        cell_value = None
        try:
            for (rlow, rhigt, clow, chigt) in self.sheet.merged_cells:
                if (rlow_index >= rlow and rlow_index < rhigt):  # 行坐标判断
                    if (clow_index >= clow and clow_index < chigt):  # 列坐标判断
                        cell_value = self.get_cell_value(rlow, clow)
                        break
                    else:
                        cell_value = self.get_cell_value(rlow_index, clow_index)
                else:
                    cell_value = self.get_cell_value(rlow_index, clow_index)
            return cell_value
        except BaseException as ba:
            return ba
    def get_sheet_data(self):
        steet1=[]
        file = self.sheet.row(0)
        # print(file)
        for row in range(1, self.get_row_count()):
            data_dict = {}
            for clos in range(0, self.get_col_count()):
                data_dict[file[clos].value] = self.get_merged_value(row, clos)
            steet1.append(data_dict)
        return steet1
    def get_testcase_data_list(self):
        testcase_list=[]
        shet = {}
        for i in self.get_sheet_data():
            shet.setdefault(i["测试用例编号"],[]).append(i)
        for k,v in shet.items():
            one_case_dict={}
            one_case_dict["case_name"]=k
            one_case_dict["case_info"]=v
            testcase_list.append(one_case_dict)
        return testcase_list


if __name__ == '__main__':
    excel=Excel_Utils("testcase_infos.xlsx","Sheet1")
    for i in excel.get_testcase_data_list():
        print(i)